package com.zz.cc.business.app;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;

import com.zz.cc.business.R;
import com.zz.cc.business.data.BsImageLoader;
import com.zz.cc.business.data.FileManager;
import com.zz.cc.business.data.ServiceType;
import com.zz.cc.business.view.ActionSheet;
import com.zz.cc.business.view.ActionSheet.OnButtonClickListener;
import com.zz.common.app.BaseActivity;
import com.zz.common.tools.ImageLoader;
import com.zz.common.tools.ImageLoader.IconFlinger;
import com.zz.common.tools.ImageLoader.IconToken;
import com.zz.common.tools.WeakReferenceHandler;
import com.zz.common.utils.ImageUtil;
import com.zz.common.utils.ZLog;
import com.zz.common.widget.ZFixedGridView;

public class BusinessDetailActivity extends BaseActivity implements OnClickListener, Callback {
	
	private static final String TAG = "BusinessDetailActivity";

	private static final int REQUEST_CODE_FOR_TAKE_PICTURE = 10000;
	private static final int REQUEST_CODE_FOR_SELECT_LOCAL_PICTURE = REQUEST_CODE_FOR_TAKE_PICTURE + 1;
	
	private Button mSubmit;
	private ZFixedGridView mServiceTypesGridView;
	
	private Button mSelectPicturesBtn;
	private ZFixedGridView mIconsGridView;
	
	private WeakReferenceHandler mHandler;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_business_detail);
		mHandler = new WeakReferenceHandler(this);
		initUI();
		fillView();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == REQUEST_CODE_FOR_TAKE_PICTURE) {
			onTaskPicture(resultCode, data);
		} else if(requestCode == REQUEST_CODE_FOR_SELECT_LOCAL_PICTURE) {
			onSelectLocalPicture(resultCode, data);
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	private void initUI() {
		mSubmit = (Button) findViewById(R.id.detail_submit);
		mServiceTypesGridView = (ZFixedGridView) findViewById(R.id.detail_services_grid_view);
		
		mSelectPicturesBtn = (Button) findViewById(R.id.detail_button_select_pictures);
		mIconsGridView = (ZFixedGridView) findViewById(R.id.detail_pictures_grid_view);
	}
	
	private void fillView() {
		mSubmit.setOnClickListener(this);
		
		mServiceTypesGridView.setColNom(2);
		mServiceTypesGridView.setCellHeightByDip(30);
		ServiceType []types = ServiceType.getAllServiceTypes();
		for(ServiceType type: types) {
			CheckBox box = new CheckBox(mServiceTypesGridView.getContext());
			box.setText(type.mTypeName);
			box.setChecked(true);
			box.setTextColor(Color.RED);
			mServiceTypesGridView.addView(box);
		}
		
		mSelectPicturesBtn.setOnClickListener(this);
		mIconsGridView.setColNom(2);
		mIconsGridView.setCellHeightByDip(100);
	}

	@Override	//View.OnClickListener
	public void onClick(View v) {
		int id = v.getId();
		if(id == R.id.detail_submit) {
			finish();
			overridePendingTransition(R.anim.activity_slide_left_in, R.anim.activity_slide_right_out);
		} else if(id == R.id.detail_button_select_pictures) {
			final ActionSheet as = ActionSheet.create(this);
			as.addButton("拍照");
			as.addButton("本地相册");
			as.addCancelButton("取消");
			as.setOnButtonClickListener(new OnButtonClickListener() {
				
				@Override
				public void OnClick(View clickedView, int which) {
					if(0 == which) {
						takePicture();
					} else {
						selectLocalPicture();
					}
					as.dismiss();
				}
			});
			
			as.setOnCancelListener(new OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface di) {}
			});
			try {	
				as.show();
			} catch(Exception e) {
				e = null;
			}
		}
	}
	
	private void takePicture() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivityForResult(intent, REQUEST_CODE_FOR_TAKE_PICTURE);
	}
	
	private void onTaskPicture(int resultCode, Intent data) {
		if(resultCode != Activity.RESULT_OK || null == data) {
			return;
		}
		Bundle bundle = data.getExtras();
		Bitmap bitmap = (Bitmap)bundle.get("data");
		FileManager fm = FileManager.getInstance();
		String filePath = fm.getWorkDir() + System.currentTimeMillis() + ".jpg";
		File file = new File(filePath);
		try {
			ImageUtil.saveBitmapFileAsJPEG(bitmap, file);
			handleNewPicture(filePath);
		} catch (IOException e) {
			e = null;
		}
	}
	
	private void selectLocalPicture() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.addCategory(Intent.CATEGORY_OPENABLE); 
        intent.setType("image/*"); 
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_CODE_FOR_SELECT_LOCAL_PICTURE);
	}
	
	private void onSelectLocalPicture(int resultCode, Intent data) {
		if(resultCode != Activity.RESULT_OK || null == data) {
			return;
		}
		Uri uri = data.getData();   
        String [] proj={MediaStore.Images.Media.DATA};  
        Cursor cursor = managedQuery( uri,  
                proj,                 // Which columns to return  
                null,       // WHERE clause; which rows to return (all rows)  
                null,       // WHERE clause selection arguments (none)  
                null);                 // Order-by clause (ascending by name)  
          
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
        cursor.moveToFirst();  
          
        String path = cursor.getString(column_index); 
//        cursor.close();
        handleNewPicture(path);
	}
	
	private void handleNewPicture(String path) {
		ZLog.d(TAG, "handleNewPicture: " + path);
		BsImageLoader.getLoader().loadIcon(path, mHandler, null);
		
	}
	
	private void onNewPicture(IconFlinger flinger) {
		if(null != flinger.mIcon) {
			ImageView imageView = new ImageView(mIconsGridView.getContext());
			imageView.setImageBitmap(flinger.mIcon);
			mIconsGridView.addView(imageView);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch(msg.what) {
		case ImageLoader.ACTION_IMAGE_LOADER:
			IconFlinger flinger = (IconFlinger) msg.obj;
			onNewPicture(flinger);
			break;
			
		default:
			break;
		}
		return false;
	}
}
